package com.cxd.blog.service.impl;

import com.alibaba.fastjson.JSON;
import com.cxd.blog.model.entity.SysUser;
import com.cxd.blog.service.SsoService;
import com.cxd.blog.service.SysUserService;
import com.cxd.blog.utils.JWTUtils;
import com.cxd.blog.model.vo.Result;
import com.cxd.blog.model.vo.ResultCode;
import com.cxd.blog.model.vo.params.LoginParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Author: PGTWO
 * @Version: 1.0
 * @Date: 2021/8/24 23:41
 * @Description:
 */
@Service
@Slf4j
public class SsoServiceImpl implements SsoService {

    private static final String slat = "ubssdic!@#";

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 1、判断参数是否合法
     * 2、判断账户是否存在 存在返回用户已经被注册 不存在则注册
     * 3、生成token 存入redis并且返回
     * 4、加上事务回滚，错误操作不能入库
     *
     * @param loginParams
     * @return
     */
    @Override
    public Result register(LoginParams loginParams) {
        String accountName = loginParams.getAccount();
        String password = loginParams.getPassword();
        String nickName = loginParams.getNickname();
        if (StringUtils.isBlank(accountName) || StringUtils.isBlank(password) || StringUtils.isBlank(nickName)) {
            return Result.fail(ResultCode.ACCOUNT_PWD_NOT_ALLOW.getCode(), ResultCode.ACCOUNT_PWD_NOT_ALLOW.getMsg());
        }
        SysUser user = sysUserService.findUserByAccountName(accountName);
        //用户信息存在
        if (user != null) {
            return Result.fail(ResultCode.ACCOUNT_IS_EXIST.getCode(), ResultCode.ACCOUNT_IS_EXIST.getMsg());
        }
        SysUser sysUser = new SysUser();
        sysUser.setAccount(accountName);
        sysUser.setNickname(nickName);
        sysUser.setPassword(DigestUtils.md5Hex(password + slat));
        sysUser.setCreateDate(System.currentTimeMillis());
        sysUser.setLastLogin(System.currentTimeMillis());
        sysUser.setAvatar("/static/img/logo.b3a48c0.png");
        //1 为true
        sysUser.setAdmin(1);
        // 0 为false
        sysUser.setDeleted(0);
        sysUser.setSalt("");
        sysUser.setStatus("");
        sysUser.setEmail("");
        sysUserService.save(sysUser);
        String token = JWTUtils.createToken(sysUser.getId());
        redisTemplate.opsForValue().set("TOKEN_" + token, JSON.toJSONString(sysUser), 1, TimeUnit.DAYS);
        return Result.success(token);
    }

    /**
     * 1、参数是否合法
     * 2、根据用户名密码去user表中查询是否存在
     * 3、不存在则登陆失败？？
     * 4、存在，使用jwt生成token 返回前端
     * 5、token放入redis中 --> token ：user信息  设置过期时间（先认证token字符串是否存在）
     *
     * @param loginParams
     * @return
     */
    @Override
    public Result login(LoginParams loginParams) {
        String accountName = loginParams.getAccount();
        String password = loginParams.getPassword();
        if (StringUtils.isEmpty(accountName) || StringUtils.isEmpty(password)) {
            return Result.fail(ResultCode.PARAMS_ERROR.getCode(), ResultCode.PARAMS_ERROR.getMsg());
        }
        String pwd = DigestUtils.md5Hex(password + slat);
        SysUser sysUser = sysUserService.findUser(accountName, pwd);
        if (sysUser == null) {
            return Result.fail(ResultCode.ACCOUNT_PWD_NOT_EXIST.getCode(), ResultCode.ACCOUNT_PWD_NOT_EXIST.getMsg());
        }
        //生成token
        String token = JWTUtils.createToken(sysUser.getId());
        log.info("token:{}",token);
        //存入redis
        redisTemplate.opsForValue().set("TOKEN_" + token, JSON.toJSONString(sysUser), 1, TimeUnit.DAYS);
        return Result.success(token);
    }

    @Override
    public Result logout(String token) {
        redisTemplate.delete("TOKEN_" + token);
        return Result.success(ResultCode.LOGOUT_CURRENT_USER.getMsg());
    }
}
